package com.test.listfiles;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class GetFileName {
    public static void main(String[] args) throws IOException {
//        getFilesAndWriteToFile("/opt/applogs");
        listFiles("/opt/applogs");
    }

    /**
     * 列出目录下的文件
     * @param path
     */
    public static void listFiles(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File f : files) {
            System.out.println("文件名：" + f);
        }
    }

    /**
     * 列出指定目录下的所有文件夹以及文件
     * @param path
     * @return
     * @throws IOException
     */
    public static ArrayList<String> getFilesAndWriteToFile(String path) throws IOException {
        ArrayList<String> files = new ArrayList<>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        File file1 =new File("fileNames.txt");
        if(!file1.exists()){
            file1.createNewFile();
        }

        BufferedWriter bufferWritter = new BufferedWriter(new FileWriter(file1.getName(),true));

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                System.out.println("文  件：" + tempList[i]);
                bufferWritter.write(tempList[i] +"\n");
                files.add(tempList[i].toString());
            } else {
                System.out.println("文件夹：" + tempList[i]);
                bufferWritter.write(tempList[i] +"\n");
                String filePath = tempList[i].toString();
                getFilesAndWriteToFile(filePath);
            }
        }
        bufferWritter.close();
        return files;
    }
}
